from sqlalchemy.orm import Session
from schema import Task_Machine_schema
from model import Task_Machine_model



def get_Task_Machine(db: Session, ID: int):
    return db.query(Task_Machine_model.Task_machine).filter(Task_Machine_model.Task_machine.ID == ID).first()


def get_all_Task_Machine(db: Session):
    return db.query(Task_Machine_model.Task_machine).all()


def delete_Task_Machine(db: Session, ID):
    to_delete = db.query(Task_Machine_model.Task_machine).filter(Task_Machine_model.Task_machine.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Task_Machine(db: Session, Task_Machine: Task_Machine_schema.Task_machine):
    db_Task_Machine = Task_Machine_model.Task_machine(
        MachineID=Task_Machine.MachineID,
        OperationID=Task_Machine.OperationID,
        Remarks=Task_Machine.Remarks,
    )
    db.add(db_Task_Machine)
    db.commit()
    db.refresh(db_Task_Machine)
    return db_Task_Machine


def update_Task_Machine(db: Session, ID, field_name, new_value):
    db_Task_Machine = db.query(Task_Machine_model.Task_machine).filter(Task_Machine_model.Task_machine.ID == ID).first()
    setattr(db_Task_Machine, field_name, new_value)
    db.commit()
    db.refresh(db_Task_Machine)
    return db_Task_Machine
